/* eslint-disable import/prefer-default-export */
import React from 'react';
import { IRoute, MicroApp } from 'umi';
import { cloneDeep } from 'lodash';

import { queryConfig } from './services/config';

let extraRoutes: IRoute[] = [];

export const qiankun = queryConfig().then(res => {
  const { apps } = res.data.data;

  return {
    apps,
  };
});

// 创建微服务
const createMicroApp = ({ match }: any, name: string) => {
  const { url } = match;
  const umiConfigBase = '';
  const runtimeMatchedBase =
    umiConfigBase + (url.endsWith('/') ? url.substr(0, url.length - 1) : url);
  return React.createElement(MicroApp, {
    name,
    base: runtimeMatchedBase,
    history: 'browser',
    settings: {},
  });
};

// 创建微应用路由
const createMicroRoute = (route: any) => {
  const cloneRoute = cloneDeep(route);
  cloneRoute.exact = false;
  cloneRoute.component = (param: any) =>
    createMicroApp(param, cloneRoute.microApp);
  return cloneRoute;
};

// 动态加载路由
export function patchRoutes({ routes }: { routes: IRoute }) {
  extraRoutes.forEach(element => {
    routes[0].routes.unshift(element);
  });
}
// 动态渲染
export async function render(oldRender: () => void) {
  queryConfig().then(res => {
    const { routes } = res.data.data;

    extraRoutes = routes.map((it: IRoute) => createMicroRoute(it));

    oldRender();
  });
}
